package com.woniuxy.user.exception;


import com.woniuxy.commons.request.ResponseResult;
import com.woniuxy.commons.request.ResultStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;

@Slf4j
public class OAuthServerWebResponseExceptionTranslator implements WebResponseExceptionTranslator {
    /**
     * 解析结果
     */
    @Override
    public ResponseEntity<ResponseResult<ResultStatus>> translate(Exception e){
        // 获取异常状态
        ResultStatus resultStatus = doTranslateHandler(e);
        // 封装数据
        ResponseResult<ResultStatus> responseResult = new ResponseResult<>();
        responseResult.setCode(resultStatus.getCode());
        responseResult.setMessage(resultStatus.getMsg());
        // 返回结果
        return new ResponseEntity<>(responseResult, HttpStatus.OK);
    }

    /**
     * 解析
     */
    private ResultStatus doTranslateHandler(Exception e) {
        // Token was not recognised  Token has expired
        // error="invalid_token", error_description="Token has expired"
        log.info("捕获异常：" + e.toString());
        log.info(e.getClass().toString());
        //初始值，系统错误，
        ResultStatus resultStatus = ResultStatus.UNAUTHORIZED;

        if(e instanceof UnsupportedGrantTypeException){
            //判断异常，不支持的认证方式
            resultStatus = ResultStatus.UNSUPPORTED_GRANT_TYPE;

        }else if(e instanceof InvalidGrantException){
            //用户名或密码异常
            if (e.getMessage().startsWith("Invalid refresh token")){
                resultStatus = ResultStatus.INVALID_REFRESH_TOKEN;
            } else if ("User account is locked".equals(e.getMessage())){
                log.info("用户账号被锁定");
                resultStatus = ResultStatus.USER_ACCOUNT_LOCKED;
            }
        }else if (e.getMessage().equals("Token was not recognised")){
            // 无效的token
            resultStatus = ResultStatus.INVALID_TOKEN;
        }else if (e.getMessage().equals("Token has expired")){
            // token过期
            resultStatus = ResultStatus.TOKEN_EXPIRE;
        }else if (e.getMessage().equals("Invalid refresh token")){
            resultStatus = ResultStatus.REFRESH_TOKEN_EXPIRE;
        }
        return resultStatus;
    }
}
